<template>
  <div style="display: flex; margin: 10px 0">
    <div style="width: 40%; ">
      <el-image :src="state.goods.img" style="width: 100%;"></el-image>
    </div>
    <div style="margin-left: 10px; flex: 1">
      <el-card>
        <el-form label-width="80px">
          <el-form-item label="商品名称">{{ state.goods.name }}</el-form-item>
          <el-form-item label="商品描述">{{ state.goods.description }}</el-form-item>
          <el-form-item label="商品价格"><span style="color: red">{{ state.goods.price }}/{{ state.goods.unit }}</span></el-form-item>
          <el-form-item label="商品库存"><span>{{ state.goods.nums }}</span></el-form-item>

          <div>
            <el-input-number :value="1" size="medium" style="width: 150px" v-model="state.buyNum" :min="1"></el-input-number>
            <el-button style="background: red; font-size: 16px; color: white; padding: 10px; margin-left: 5px" @click="addCart">加入购物车</el-button>
          </div>

          <div style="margin-top: 20px; font-size: 12px; color: #888">
            温馨提示
            <div>·支持7天无理由退货·谨防用电安全隐患，请依照产品说明书使用此类工具并采取必要人身防护措施，日常置于儿童无法触及处。</div>
          </div>
        </el-form>
      </el-card>
    </div>
  </div>

</template>

<script setup>
import request from "../../request.js";
import {onMounted, reactive} from "vue";
import {useRoute} from "vue-router";
import {ElMessage, ElNotification} from "element-plus";
import {number} from "echarts";
const $route = useRoute()
let id = $route.query
const state = reactive({
  goods:[],
  buyNum:1,
  userid:localStorage.getItem('userid'),
  cart:{}
})
// onMounted(() => {
//   window.onbeforeunload = function (e) {
//     let storage = window.localStorage;
//     storage.clear();
//   };
// })

const load = () => {
  request.get("/goods/" + id.id).then(res => {
    state.goods = res.data
    console.log(res)
  })
}
load()

const addCart = () => {
  state.cart.num = state.buyNum
  state.cart.goods_id = state.goods.id
  state.cart.user_id = state.userid
  console.log(state.cart, state.userid)
  if(state.userid == null){
    ElNotification.error("请先登录")
  }else{
      request.post("/cart", state.cart).then(res => {
        if(res.code == '200'){
          ElNotification.success("添加成功")
        }else{
          ElNotification.error("添加失败")
        }
      })
  }
}
</script>

<style scoped>

</style>